var app = getApp(), u = app.require("utils/util.js"), a = app.require("utils/api.js"), o = app.require("utils/onfire.js"), h = app.require("utils/http.js"), n = app.require("utils/enums");

var initdata = function (that) {
  var cartList = that.data.cartList
  for (var i = 0; i < cartList.length; i++) {
    cartList[i].shows = ""
  }
  that.setData({
    cartList: cartList
  })
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:null,
    delBtnWidth: 120, //删除按钮宽度单位（rpx） 
    cartList:[],
    isAllChecked:false,
    isIncludeRecipe:false,
    account:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    this.initEleWidth();
  },
  onShow: function () {
    var t = this;
    app.getToken();
    
    if (wx.getStorageSync('userInfo')) {
      t.data.userInfo = wx.getStorageSync('userInfo'), 
      t.getCartList();
    }else{
      app.callAuthorize(function (userinfo) {
        t.getCartList();
      });
    }   
  },
  onHide: function () {
    // 更新购物车数量
    for (var i = 0; i < this.data.cartList.length; i++) {
      this.updateCartNum(this.data.cartList[i]);
    }    
  },
  // 获取购物车记录
  getCartList: function (userinfo){
    var t = this;
    var data = {
      store_id: a.storeId,
      uid: userinfo ? userinfo.uid : t.data.userInfo.uid
    };
    h.postReq(a.getCartList, data, function (res) {
      if(res.code == 0){
        var cart_list = res.data.cart_list;
        for (var i = 0; i < cart_list.length; i++){
          cart_list[i]['checked'] = true;
        }
        t.isAllCheckedfun(cart_list),
        t.imputedPrice(cart_list),
        t.setData({ cartList: cart_list }), 
        t.isIncludeRecipe(t.data.cartList);
      }
    });
  },
  // 商品详情
  proudctInfo: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/index/product/info?id=' + id
    })
  },
  // 更新购物车商品数量
  updateCartNum:function(cart){
    var t = this;
    var data = {
      store_id: a.storeId,
      uid: t.data.userInfo.uid,
      id: cart.pigcms_id,
      num: cart.pro_num,
      product_id: cart.product_id
    };
    h.postReq(a.updateCartNum, data, function (res) {
      if(res.code == 0){
        console.log(res.message);
      }else{
        console.log(res.message);
      }
    });
  },
  // 更改选中状态
  bindChecked:function(e){
    var t = this;
    var index = e.currentTarget.dataset.index;
    if (t.data.cartList[index]['checked']){
      t.data.cartList[index]['checked'] = false;
    }else {
      t.data.cartList[index]['checked'] = true;
    }
    t.setData({ cartList: t.data.cartList }),
    t.isAllCheckedfun(t.data.cartList), 
    t.isIncludeRecipe(t.data.cartList),
    t.imputedPrice(t.data.cartList);
  },
  // 商品全部选中
  bindAll:function(e){
    var t = this;
    if (t.data.isAllChecked){
      for (var i = 0; i < t.data.cartList.length; i++) {
        t.data.cartList[i]['checked'] = false;
      }
      t.setData({ 
        isAllChecked: false,
        cartList: t.data.cartList
      });
    }else{
      for (var i = 0; i < t.data.cartList.length; i++) {
        t.data.cartList[i]['checked'] = true;
      }
      t.setData({
        isAllChecked: true, cartList: t.data.cartList
      });
    }
    t.imputedPrice(t.data.cartList);
  },
  // 判断是否全选 
  isAllCheckedfun:function(nowCartList){
    var t = this;
    var flag = 1;
    nowCartList.length <= 0 ? flag = 0 : flag = 1; 
    for (var i = 0; i < nowCartList.length; i++) {
      if (!nowCartList[i]['checked']){
        flag = 0;
      }
    } 
    flag == 1 ? t.setData({ isAllChecked: true }) : t.setData({ isAllChecked: false });
  },
  // 判断是否包含处方药
  isIncludeRecipe: function (nowCartList){
    var t = this;
    var flag = 0;
    for (var i = 0; i < nowCartList.length; i++) {
      if (nowCartList[i]['checked'] && nowCartList[i]['type'] == 2) {
        flag = 1;
      }
    } 
    flag == 1 ? t.setData({ isIncludeRecipe: true }) : t.setData({ isIncludeRecipe: false });
  },
  // 数量增加
  minus:function(e){
    var t = this;
    var index = parseInt(e.currentTarget.dataset.index);
    t.data.cartList[index].pro_num -= 1;
    if (t.data.cartList[index].pro_num < 1){
      t.data.cartList[index].pro_num = 1;
    }
    t.imputedPrice(t.data.cartList);
    this.setData({
      cartList: t.data.cartList
    });
  },
  // 数量减少
  plus:function(e){
    var t = this;
    var index = parseInt(e.currentTarget.dataset.index);
    t.data.cartList[index].pro_num  += 1;
    if (t.data.cartList[index].pro_num > 99) {
      t.data.cartList[index].pro_num = 99;
    }
    t.imputedPrice(t.data.cartList);
    this.setData({
      cartList: t.data.cartList
    });
  },
  // 手动更改数量
  inputChange:function(e){
    var t = this;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    t.data.cartList[index].pro_num = value !== '' ? parseInt(value) : '';
    // if (t.data.cartList[index].pro_num <= 0) {
    //   t.data.cartList[index].pro_num = 1;
    // }    
    t.imputedPrice(t.data.cartList);
    this.setData({
      cartList: t.data.cartList
    });
  },
  // 输入框失去焦点事件
  blurInput:function(e){
    // console.log(e);
    var t = this;
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    t.data.cartList[index].pro_num = value !== '' ? parseInt(value) : '';
    if (t.data.cartList[index].pro_num <= 0){
      t.data.cartList[index].pro_num = 1;
    }
    if (t.data.cartList[index].pro_num > 99) {
      t.data.cartList[index].pro_num = 99;
    }
    t.imputedPrice(t.data.cartList);
    this.setData({
      cartList: t.data.cartList
    });
  },
  // 删除购物车商品
  delCart: function (e) {
    var t = this;
    var index = e.currentTarget.dataset.index;
    var data = {
      store_id: a.storeId,
      uid: t.data.userInfo.uid,
      ids:t.data.cartList[index].pigcms_id
    };  
    u.confirm('确定从药品清单中删除此药品？', function (res) {      
      h.postReq(a.delCartProduct, data, function (res) {
        if(res.code == 0){
          t.data.cartList.splice(index,1);
          t.isAllCheckedfun(t.data.cartList);
          t.imputedPrice(t.data.cartList);
          t.setData({ cartList:t.data.cartList});
        }
      });
    });
  },
  // 计算合计价格
  imputedPrice:function(data){
    var t = this;
    var account = 0;
    var multiple = 100;
    for (var i = 0; i < data.length; i++) {
      if (data[i].checked){
        account += data[i].pro_num * multiple * data[i].pro_price * multiple;
      }
    }
    t.setData({
      account: account / (multiple * multiple)
    });
  },
  // 去结算，问医生
  goPay: function () {
    var t = this;
    if (t.data.cartList.length <= 0) {
      return false;
    } else {
      t.data.isIncludeRecipe ? t.consultDoctor() : t.createOrder(); 
    }
  },
  // 创建订单
  createOrder: function () {
    var t = this;
    var data = {
      store_id: a.storeId,
      uid: t.data.userInfo.uid,
      ids: []
    };
    for (var i = 0; i < t.data.cartList.length; i++) {
      if (t.data.cartList[i].checked) {
        data.ids.push(t.data.cartList[i].pigcms_id);
      }
    }
    h.postReq(a.carPay, data, function (res) {
      if (res.code == 0) {
        var order_no = res.data.order_no;
        wx.navigateTo({
          url: '/pages/order/pay/index?order_no=' + order_no,
        })
      } else if (res.code == 401){
        u.toast('请至少选择一个商品');
      }else{
        u.toast(res.message);
      }
    });
  },
  // 购物车跳转问医生
  consultDoctor: function () {
    var t = this;
    var proJson = [];    
    for (var i = 0; i < t.data.cartList.length; i++) {
      var pro = {};
      if (t.data.cartList[i].checked) {
        pro.em_id = t.data.cartList[i].em_id;
        pro.pro_num = t.data.cartList[i].pro_num;
        proJson.push(pro);
      }      
    }    
    var proString = escape(JSON.stringify(proJson));
    // console.log(proString);return;
    wx.navigateTo({
      url: "/template/prescribe/prescribe?url=https://tc2.zmmedical.cn/Patient/Index/quickIndex.htm&pro_string=" + proString
    });
  },
  // 开始滑动事件
  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置 
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    var that = this;
    initdata(that)
    if (e.touches.length == 1) {
      //手指移动时水平方向位置 
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值 
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      // var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
        // txtStyle = "left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
        // txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度 
          // txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
    }
  },
  // 滑动中事件
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置 
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离 
      var disX = this.data.startX - endX;
      console.log(disX);
      // var delBtnWidth = this.data.delBtnWidth;
      var delBtnWidth = 100;
      //如果距离小于删除按钮的1/2，不显示删除按钮 
      var txtStyle = "";
      console.log(delBtnWidth);
      txtStyle = disX > delBtnWidth ? "left:-60px" : "left:0px";

      //获取手指触摸的是哪一项 
      var index = e.currentTarget.dataset.index;
      var cartList = this.data.cartList;
      cartList[index].shows = txtStyle;
      // console.log("1", cartList[index].shows);
      //更新列表的状态 
      this.setData({
        cartList: cartList
      });
    } else {
      console.log("2");
    }
  },
  //获取元素自适应后的实际宽度 
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2); //以宽度750px设计稿做宽度的自适应       
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },  
  
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh() {
    var t = this;
    // 增加下拉刷新数据的功能
    t.getCartList();
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },
})